import * as types from './mutations-types'
import {playMode} from 'common/js/config'
import {shuffle} from 'common/js/util'
import {saveSearch,deleteSearchOne,clearSearch} from 'common/js/cache'

export const selectPlay = function({commit,state},{list,index}){
    commit(types.SET_SENQUENCELIST,list)
    if(state.mode === playMode.random){
        let randomlist = shuffle(list)
        commit(types.SET_PLAYLIST,randomlist)
        index = getIndex(randomlist,list[index])
    }else{
        commit(types.SET_PLAYLIST,list)
    }
    commit(types.SET_FULL_SCREEN,true)
    commit(types.SET_CURRENT_INDEX,index)
    commit(types.SET_PLAYING_STATE,true)
}

export const randomPlay = function( {commit},{list} ){
    commit(types.SET_PLAY_MODE,playMode.random)
    commit(types.SET_SENQUENCELIST,list)
    let randomlist = shuffle(list)
    commit(types.SET_PLAYLIST,randomlist)
    commit(types.SET_FULL_SCREEN,true)
    commit(types.SET_CURRENT_INDEX,0)
    commit(types.SET_PLAYING_STATE,true)
}

export const insertSong = function ({commit,state},song){
    let playlist = state.playList.slice()
    let sequenceList = state.sequenceList.slice()
    let currentIndex = state.currentIndex
    // 记录当前歌曲
    let currentSong =  playlist[currentIndex]
    // 查找当前列表中是否有待插入的歌曲并返回其索引
    let fpIndex = getIndex(playlist,song)
    // 因为是插入歌曲 所以索引+1
    currentIndex++
    // 插入这首歌到当前索引位置
    playlist.splice(currentIndex,0,song)
    // 如果已经包含了这首歌
    if(fpIndex > -1){
        // 如果当前插入的序号大于列表中的序号
        if(currentIndex > fpIndex){
            playlist.splice(fpIndex,1)
            currentIndex--
        }else{
            playlist.splice(fpIndex + 1,1)
        }
    }

    let currentSIndex = getIndex(sequenceList,currentSong) + 1

    let fsIndex = getIndex(sequenceList,song)

    sequenceList.splice(currentSIndex,0,song)

    if(fsIndex > -1){
        if(currentSIndex > fsIndex){
            sequenceList.splice(fsIndex,1)
        }else{
            sequenceList.splice(fsIndex + 1,1)
        }
    }

    commit(types.SET_PLAYLIST,playlist)
    commit(types.SET_SENQUENCELIST,sequenceList)
    commit(types.SET_CURRENT_INDEX,currentIndex)
    commit(types.SET_FULL_SCREEN,true)
    commit(types.SET_PLAYING_STATE,true)
}
// 保存搜索历史  并存入localStorage 
export const saveSearchHistory = function ({commit},query){
    commit(types.SET_SEARCHHISTORY,saveSearch(query))

}
// 删除搜索历史 其中一条数据
export const deleteSearchHistory = function({commit},query){
    commit(types.SET_SEARCHHISTORY,deleteSearchOne(query))
}

// 清空搜索历史
export const clearSearchHistory = function({commit}){
    commit(types.SET_SEARCHHISTORY,clearSearch())
} 


// 返回第一个符合要求的item的索引
function getIndex(list,song){
    return list.findIndex((item) => {
        return item.id === song.id
    })
}